// // packageBailing/page/bailing/index.js

const api = require("../../../config/api");

var app = getApp();

let cosWX;
if (app.globalData.env == 'release') {
  cosWX = require('../../../lib/cos-wx-sdk-v5.min')
} else {
  cosWX = require('../../../lib/cos-wx-sdk-v5')
}
let cos;

let rm; 


Page({
  data: {
    hasRecord: false,
    isDot: "block",
    
    value: '100',
    

    recording: false,
    hasRecord2: false,
    recordPath: '',
    isTouchStart: false,  // 长按开始
    isTouchEnd: false,
    touchStart: 0,  // 长按开始时间
    touchEnd: 0,  // 录音结束时间,

    chatList: [],
    refreshing: false,
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    var a = this;
    wx.authorize({
      scope: "scope.record",
      success: function() {
        console.log("录音授权成功");
      },
      fail: function() {
        console.log("录音授权失败");
      }
    }), a.onShow()

    rm = wx.getRecorderManager();

    // 录音停止时调用
    rm.onStop((e) => {
      wx.showLoading();
      const name = new Date().getTime() + '.mp3';
      const key = '/record/user/' + name;
      
      cos.uploadFile({
        Bucket: 'wenling-1301798378',
        Region: 'ap-shanghai',  
        Key:  key,    /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        
        FilePath: e.tempFilePath, /* 上传文件路径，必须字段 */
        SliceSize: 1024 * 1024 * 5,     /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function(progressData) {
            console.log(JSON.stringify(progressData));
        },
      
      }, (err, data) => {
        wx.hideLoading();
        if (err) {
          console.log('上传失败', err);
        } else {
          // sendToOpenAI,转成文本，并生成对话，并返回
          
          // 提交
          
          wx.showLoading();
          wx.request({
            url: api.submitConversation,
            method: "POST",
            timeout: 60000,
            data: {
              uploadSpeech: {
                recordKey: key,
                recordName: name
              }
            },
            success: (res) => {
              console.log('submitConversation success: ' + res)
              wx.hideLoading()
              if (res.data.code == 1000) {
                const chatCompletion = res.data.data
              
                this.data.chatList.push(chatCompletion)
                this.setData({
                  chatList: this.data.chatList
                })
              } else {
                console.log(res.data)
                wx.showToast({
                  title: 'submitConversation, business fail: ' + res.data.msg,
                })
              }
            },
            fail: (e) => { 
              console.log('submitConversation fail')
              wx.hideLoading()
              console.log(e)
              wx.showToast({
                title: 'submitConversation,fail: ' + e,
              })
            },
           
          })
        }

      });




    })

    rm.onStart((e) => {
      console.log('start.....')
      console.log(e)
    })

    cos = new cosWX({
      getAuthorization: (options, callback) => {
        
        // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
        // 异步获取临时密钥
        wx.request({
          url: api.getCOSToken,
          method: "GET",
          data: {
            businessType: 'wenling'
          },
          success: (res) => {
            
            if (res.data.code == 1000) {
              const credentials = res.data.data
              callback({
                TmpSecretId: credentials.tmpSecretId,
                TmpSecretKey: credentials.tmpSecretKey,
                // v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
                SecurityToken: credentials.sessionToken,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: credentials.startTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: credentials.expiredTime, // 时间戳，单位秒，如：1580000900

              })
            }
          },
          fail: (e) => { 
            console.log(e)
            wx.showToast({
              title: 'fail: ' + e,
            })
          }
        })
      },
      SimpleUploadMethod: 'pubObject'
    })
    
  },
     
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  },

  onRefresh: function() {
    this.setData({ refreshing: true });
    // 模拟网络请求
    // setTimeout(() => {
    //   this.loadChatList();
    //   this.setData({ refreshing: false });
    // }, 2000);
  },


  // 点击录音按钮
  onRecordClick: function () {
    wx.getSetting({
      success: function (t) {
        console.log(t.authSetting), t.authSetting["scope.record"] ? console.log("已授权录音") : (console.log("未授权录音"),
          wx.openSetting({
            success: function (t) {
              console.log(t.authSetting);
            }
          }));
      }
    });
  },

  /**
   * 长按录音开始
   */
  recordStart: function(e) {
    
    if (this.data.isTouchStart)  {
      return
    }
    const options = {
      duration: 20 * 1000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    
    this.setData({
      recording: true,
      isTouchStart: true,
      isTouchEnd: false,
      touchStart: e.timeStamp,
      touchEnd: 0,
      showPg: true

    }) 
    rm.start(options)
    var n = this;
    var a = 15, o = 10;
      this.timer = setInterval(function () {
        
        n.setData({
          value: n.data.value - 100 / 1500
        }), (o += 10) >= 1e3 && o % 1e3 == 0 && (a-- , console.log(a), a <= 0 && (rm.stop(),
          console.log(n),
          clearInterval(n.timer),  n.setData({
            showPg: false,
            isTouchEnd: true,
            isTouchStart: false,
            // touchEnd: e.timeStamp,
            value: 100
          }), console.log('aaaa')));
      }, 10);
  },

  /**
   * 处理录音后的手势滑动
   * @param {*} e 
   */
  handleTouchMove: function(e) {
    if (this.data.isTouchStart) {
      let query = wx.createSelectorQuery();
      query.select('.dot').boundingClientRect();
      query.exec((res) => {
        // res[0] 是目标元素的位置和尺寸信息
        let targetInfo = res[0];
        let touch = e.changedTouches[0]; // 获取触摸点信息

        if (touch.clientX < targetInfo.left || touch.clientX > targetInfo.right ||
            touch.clientY < targetInfo.top || touch.clientY > targetInfo.bottom) {
          // console.log('触摸点移出元素区域');
          this.setData({
            isTouchEnd: true,
            isTouchStart: false,
            touchEnd: e.timeStamp,
            showPg: false,
            value: 100
          })
          clearInterval(this.timer);
          wx.showToast({title: '用户取消语音输入', icon: 'none'})
        } else {
          // console.log('触摸点未移出元素区域');
        }
      });
    }
  },

  /**
   * 长按录音结束
   */
  recordTerm: function(e) {
    
    if (this.data.isTouchEnd) {
      return
    }
    rm.stop()
    this.setData({
      isTouchEnd: true,
      isTouchStart: false,
      touchEnd: e.timeStamp,
      showPg: false,
      value: 100
    })
    clearInterval(this.timer);
  },
  
})

